package com.atguigu.day04;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//5个线程读，5个线程写入，操作同一个资源

class MyCache{
    volatile Map<String,String> map = new HashMap<>();
    //写方法
    //1  不加锁     不可以，写的时候原子性被破坏
    //2    加ReentrantLock 锁   写控制了，但是没有并发锁，并发性能不好
    //v1   普通锁
//    Lock lock = new ReentrantLock();
//    public void write(String key,String value){
//        lock.lock();
//        try {
//
//            System.out.println(key+"开始写入");
//            map.put(key,value);
//            System.out.println(key+"结束写入");
//        }finally{
//            lock.unlock();
//        }
//
//    }
//    //读方法
//    public void read(String key){
//        lock.lock();
//        try {
//            System.out.println(key+"开始读取");
//            String value = map.get(key);
//            System.out.println(key+"结束读取"+value);
//        }finally{
//            lock.unlock();
//        }
//    }

    // v2   读写锁
//    Lock lock = new ReentrantLock();
    ReadWriteLock rWLock = new ReentrantReadWriteLock();
    public void write(String key,String value){
        rWLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"-------开始写入");
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"\t"+"-------结束写入");
        }finally{
            rWLock.writeLock().unlock();
        }

    }
    //读方法
    public void read(String key){
        rWLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t" +"开始读取");
            String value = map.get(key);
            System.out.println(Thread.currentThread().getName()+"\t"+"结束读取"+value);
        }finally{
            rWLock.readLock().unlock();
        }
    }
}

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache =  new MyCache();
        for (int i = 1; i <= 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.write(finalI+"",finalI+"");
            }, String.valueOf(i)).start();
        }

        //线程睡眠几秒
   //     try {
 //           TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
             for (int i = 1; i <= 5; i++) {
                 int finalI =i;
                new Thread(() -> {
                    myCache.read(finalI+"");
                        }, String.valueOf(i)).start();
             }
}
}
